﻿// -----------------------------------------------------------------------
// <copyright file="PositionDataSource.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Proto
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    using Proto.Fields;
    using Proto.Providers;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class PositionDataSource
    {
        public const int NUM_ITEMS = 1000;
        private readonly Dictionary<BookCode, NotifyList<Position>> m_ListLookup;

        private readonly Thread Op;
        public PositionDataSource()
        {
            m_ListLookup = new Dictionary<BookCode, NotifyList<Position>>();
            Op = new Thread(Start);

        }

        private void Start()
        {
            Thread.Sleep( 5000 );

            Random r = new Random();
            while( RunnerRegistry.INTEGRATION.Thread.IsAlive )
            {

                    Thread.Sleep(r.Next(100, 300));
                    RunnerRegistry.INTEGRATION.Enqueue(delegate
                    {
                        foreach (BookCode code in m_ListLookup.Keys)
                        {
                            NotifyList<Position> list = m_ListLookup[code];
                            for (int i = 0; i < list.Count; i++)
                            {
                                Position p = list[i];
                                int qty = p.Quantity + r.Next(-10, 10);
                                p.Quantity = (Quantity)qty;
                                list[i] = p;

                            }
                        }
                        
                    });
            }
        }

        public NotifyList<Position> GetPositions(BookCode book_code)
        {

                Random r = new Random();
                NotifyList<Position> list;

                //lock (m_ListLookup)
                //{
                    
                    if (m_ListLookup.TryGetValue(book_code, out list) == false)
                    {
                        Thread.Sleep(r.Next(10, 50));

                        list = new NotifyList<Position>();
                        for (int i = 0; i < NUM_ITEMS; i++)
                        {
                            Position p = new Position(book_code, (RIC)i.ToString(), (Quantity)i);
                            list.Add(p);
                        }

                        m_ListLookup.Add(book_code, list);
                    }
                    if (Op.IsAlive == false) Op.Start();
            //});
            return list;
        }
    }
}
